<template>
  <div class="news-layout">
    <!-- 顶部导航 -->
    <div class="news-header">
      <div class="header-content">
        <div class="header-left">
          <el-button text @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            返回首页
          </el-button>
          <div class="breadcrumb">
            <span>资讯中心</span>
            <el-icon><ArrowRight /></el-icon>
            <span>{{ currentTitle || '最新资讯' }}</span>
          </div>
        </div>
        
        <div class="header-right">
          <el-button @click="toggleSubscription">
            <el-icon><Bell /></el-icon>
            {{ isSubscribed ? '已订阅' : '订阅推送' }}
          </el-button>
          <el-button @click="toggleSettings">
            <el-icon><Setting /></el-icon>
            设置
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="news-main">
      <router-view />
    </div>

    <!-- 订阅设置抽屉 -->
    <el-drawer
      v-model="showSettings"
      title="推送设置"
      direction="rtl"
      size="350px"
    >
      <div class="settings-content">
        <div class="setting-group">
          <label>推送通知</label>
          <el-switch v-model="newsSettings.pushNotification" @change="handlePushChange" />
          <div class="setting-desc">开启后会推送最新资讯</div>
        </div>
        
        <div class="setting-group">
          <label>推送频率</label>
          <el-select v-model="newsSettings.pushFrequency" @change="handleFrequencyChange">
            <el-option label="实时推送" value="realtime" />
            <el-option label="每日推送" value="daily" />
            <el-option label="每周推送" value="weekly" />
            <el-option label="关闭推送" value="none" />
          </el-select>
          <div class="setting-desc">选择接收推送的频率</div>
        </div>
        
        <div class="setting-group">
          <label>关注分类</label>
          <div class="category-checkboxes">
            <el-checkbox-group v-model="newsSettings.categories" @change="handleCategoryChange">
              <el-checkbox label="技术动态">技术动态</el-checkbox>
              <el-checkbox label="行业资讯">行业资讯</el-checkbox>
              <el-checkbox label="学习资源">学习资源</el-checkbox>
              <el-checkbox label="职场发展">职场发展</el-checkbox>
              <el-checkbox label="开源项目">开源项目</el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="setting-desc">选择您感兴趣的资讯分类</div>
        </div>
        
        <div class="setting-group">
          <label>推送时间</label>
          <el-time-picker
            v-model="newsSettings.pushTime"
            format="HH:mm"
            placeholder="选择推送时间"
            @change="handleTimeChange"
          />
          <div class="setting-desc">设置每日推送的时间</div>
        </div>
        
        <div class="setting-group">
          <label>邮件推送</label>
          <el-switch v-model="newsSettings.emailPush" @change="handleEmailChange" />
          <div class="setting-desc">通过邮件接收资讯摘要</div>
        </div>
        
        <div class="setting-actions">
          <el-button @click="resetSettings">重置设置</el-button>
          <el-button type="primary" @click="saveSettings">保存设置</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 快速搜索 -->
    <div class="quick-search" v-if="showQuickSearch">
      <div class="search-overlay" @click="hideQuickSearch"></div>
      <div class="search-modal">
        <div class="search-header">
          <h3>搜索资讯</h3>
          <el-button text @click="hideQuickSearch">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        
        <div class="search-input">
          <el-input
            v-model="searchKeyword"
            placeholder="输入关键词搜索资讯..."
            size="large"
            @keyup.enter="performSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #suffix>
              <el-button @click="performSearch">搜索</el-button>
            </template>
          </el-input>
        </div>
        
        <div class="search-suggestions" v-if="searchSuggestions.length > 0">
          <div class="suggestions-title">热门搜索</div>
          <div class="suggestions-list">
            <el-tag
              v-for="suggestion in searchSuggestions"
              :key="suggestion"
              @click="searchBySuggestion(suggestion)"
              class="suggestion-tag"
            >
              {{ suggestion }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { 
  ArrowLeft, ArrowRight, Bell, Setting, Close, Search
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()

// 响应式数据
const showSettings = ref(false)
const showQuickSearch = ref(false)
const isSubscribed = ref(false)
const searchKeyword = ref('')

// 计算当前页面标题
const currentTitle = computed(() => {
  return route.meta?.title || ''
})

// 推送设置
const newsSettings = ref({
  pushNotification: true,
  pushFrequency: 'daily',
  categories: ['技术动态', '行业资讯'],
  pushTime: new Date('2024-01-01 09:00:00'),
  emailPush: false
})

// 搜索建议
const searchSuggestions = ref([
  'Vue.js 3.0',
  'JavaScript ES2024',
  'React 18',
  'TypeScript',
  '前端框架',
  '人工智能',
  '机器学习',
  '云计算'
])

// 方法
const goBack = () => {
  router.push('/')
}

const toggleSubscription = () => {
  isSubscribed.value = !isSubscribed.value
  ElMessage.success(isSubscribed.value ? '已订阅资讯推送' : '已取消订阅')
}

const toggleSettings = () => {
  showSettings.value = !showSettings.value
}

const showQuickSearchModal = () => {
  showQuickSearch.value = true
}

const hideQuickSearch = () => {
  showQuickSearch.value = false
  searchKeyword.value = ''
}

const performSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  router.push({
    path: '/news/search',
    query: { q: searchKeyword.value }
  })
  hideQuickSearch()
}

const searchBySuggestion = (suggestion) => {
  searchKeyword.value = suggestion
  performSearch()
}

const handlePushChange = (enabled) => {
  ElMessage.success(`推送通知已${enabled ? '开启' : '关闭'}`)
}

const handleFrequencyChange = (frequency) => {
  const frequencyText = {
    'realtime': '实时推送',
    'daily': '每日推送',
    'weekly': '每周推送',
    'none': '关闭推送'
  }
  ElMessage.success(`推送频率已设置为${frequencyText[frequency]}`)
}

const handleCategoryChange = (categories) => {
  ElMessage.success(`已更新关注分类，共选择${categories.length}个分类`)
}

const handleTimeChange = (time) => {
  ElMessage.success('推送时间已更新')
}

const handleEmailChange = (enabled) => {
  ElMessage.success(`邮件推送已${enabled ? '开启' : '关闭'}`)
}

const resetSettings = () => {
  newsSettings.value = {
    pushNotification: true,
    pushFrequency: 'daily',
    categories: ['技术动态', '行业资讯'],
    pushTime: new Date('2024-01-01 09:00:00'),
    emailPush: false
  }
  ElMessage.success('设置已重置')
}

const saveSettings = () => {
  // 保存设置到本地存储
  localStorage.setItem('news-settings', JSON.stringify(newsSettings.value))
  ElMessage.success('设置已保存')
}

// 键盘快捷键
const handleKeydown = (event) => {
  // Ctrl/Cmd + K 打开快速搜索
  if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
    event.preventDefault()
    showQuickSearchModal()
  }
  
  // ESC 关闭快速搜索
  if (event.key === 'Escape' && showQuickSearch.value) {
    hideQuickSearch()
  }
}

// 生命周期
onMounted(() => {
  // 从本地存储加载设置
  const savedSettings = localStorage.getItem('news-settings')
  if (savedSettings) {
    try {
      newsSettings.value = { ...newsSettings.value, ...JSON.parse(savedSettings) }
    } catch (error) {
      console.warn('Failed to load news settings:', error)
    }
  }
  
  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeydown)
})

// 清理
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style lang="scss" scoped>
.news-layout {
  min-height: 100vh;
  background: var(--el-bg-color-page);
  display: flex;
  flex-direction: column;
}

.news-header {
  background: white;
  border-bottom: 1px solid var(--el-border-color-extra-light);
  padding: 16px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
  
  .breadcrumb {
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--el-text-color-secondary);
    font-size: 14px;
  }
}

.header-right {
  display: flex;
  gap: 12px;
}

.news-main {
  flex: 1;
  overflow: hidden;
}

.settings-content {
  .setting-group {
    margin-bottom: 24px;
    
    label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
    
    .setting-desc {
      margin-top: 4px;
      font-size: 12px;
      color: var(--el-text-color-placeholder);
    }
    
    .el-select,
    .el-time-picker {
      width: 100%;
    }
    
    .category-checkboxes {
      .el-checkbox-group {
        display: flex;
        flex-direction: column;
        gap: 8px;
      }
    }
  }
  
  .setting-actions {
    display: flex;
    gap: 12px;
    padding-top: 20px;
    border-top: 1px solid var(--el-border-color-extra-light);
    
    .el-button {
      flex: 1;
    }
  }
}

.quick-search {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2000;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 10vh;
}

.search-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
}

.search-modal {
  position: relative;
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow: hidden;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px 16px;
  border-bottom: 1px solid var(--el-border-color-extra-light);
  
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin: 0;
  }
}

.search-input {
  padding: 20px 24px;
  
  .el-input {
    :deep(.el-input__wrapper) {
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }
}

.search-suggestions {
  padding: 0 24px 24px;
  
  .suggestions-title {
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-secondary);
    margin-bottom: 12px;
  }
  
  .suggestions-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    
    .suggestion-tag {
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:hover {
        background: var(--el-color-primary);
        color: white;
      }
    }
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 12px;
  }
  
  .header-left,
  .header-right {
    width: 100%;
    justify-content: center;
  }
  
  .search-modal {
    width: 95%;
    margin: 0 auto;
  }
  
  .search-input,
  .search-header,
  .search-suggestions {
    padding-left: 16px;
    padding-right: 16px;
  }
}
</style>
